import time
import uuid


class RedLock:
    def __init__(self, redis_client, lock_key):
        self.redis_client = redis_client
        self.lock_key = lock_key
        self.lock_value = str(uuid.uuid4())

    def acquire_lock(self, timeout=10):
        end_time = time.time() + timeout
        while time.time() < end_time:
            if self.redis_client.setnx(self.lock_key, self.lock_value):
                # 锁设置成功
                return True
            time.sleep(0.001)  # 短暂休眠避免频繁请求
        return False  # 获取锁失败

    def release_lock(self):
        if self.redis_client.get(self.lock_key) == self.lock_value:
            self.redis_client.delete(self.lock_key)

